<template>
  <view :style="wkStyle">
    <zh-sheet
      :text="props.text"
      :border="0"
      hover-class="opacity-6"
      :transprent="props.transprent"
      :height="props.height"
      :width="_colWidth - 0.5"
      :margin="[0, 0, 0, 20]"
      :padding="[0, 0]"
      _class="flex-col flex"
      @click="onClick"
    >
      <view class="flex-1 flex flex-col-center-center">
        <zh-badge :top="0" :userInteractionEnabled="true" :fontSize="20" :dot="props.dot" :count="props.count" :max-count="props.maxCount" :icon="props.icon" :color="props.color">
          <view class="flex-col flex-col-center-center flex px-10 my-5" :class="[props.dot ? '' : 'py-5 ']">
            <slot>
              <view v-if="props.linkItem.bgColor">
                <view v-if="_col==1">
                  <view class="flex-row-center-center"  :style="{backgroundColor:props.linkItem.bgColor,borderRadius:props.iconRound+'rpx',width:(_colWidth-80)+'rpx',height:'120rpx'}">
                    <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="80" :color="props.linkItem.color" ></tm-icon>
                    <zh-text _class="text-weight-b pl-20" parentClass="text-align-center" :font-size="48" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
                  </view>
                </view>
                <view v-else-if="_col==2">
                  <view class="flex-row-center-center"  :style="{backgroundColor:props.linkItem.bgColor,borderRadius:props.iconRound+'rpx',width:(_colWidth-80)+'rpx',height:'200rpx'}">
                    <view>
                    <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="80" :color="props.linkItem.color" ></tm-icon>
                    <zh-text _class="text-weight-b" parentClass="text-align-center" :font-size="38" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
                    </view>
                  </view>
                </view>
                <view v-else-if="_col==3" class="flex-col flex-col-center-center flex">
                  <view>
                  <view class="flex-row-center-center"  :style="{backgroundColor:props.linkItem.bgColor,borderRadius:props.iconRound+'rpx',width:(_colWidth-100)+'rpx',height:(_colWidth-100)+'rpx'}">
                    <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="64" :color="props.linkItem.color" ></tm-icon>
                  </view>
                  <zh-text _class="text-weight-b  mt-10" parentClass="text-align-center" :font-size="32" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
                  
                </view>
                </view>
                <view v-else-if="_col==4" class="flex-col flex-col-center-center flex">
                  <view class="flex-row-center-center"  :style="{backgroundColor:props.linkItem.bgColor,borderRadius:props.iconRound+'rpx',width:(_colWidth-80)+'rpx',height:(_colWidth-80)+'rpx'}">
                    <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="40" :color="props.linkItem.color" ></tm-icon>
                  </view>
                  <zh-text _class="text-weight-b mt-10" parentClass="text-align-center" :font-size="28" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
                </view>
                <view v-else class="flex-col flex-col-center-center flex">
                  <view class="flex-row-center-center"  :style="{backgroundColor:props.linkItem.bgColor,borderRadius:props.iconRound+'rpx',width:(_colWidth-40)+'rpx',height:(_colWidth-40)+'rpx'}">
                    <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="36" :color="props.linkItem.color" ></tm-icon>
                  </view>
                  <zh-text _class="text-weight-b mt-10" parentClass="text-align-center" :font-size="28" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
                </view>
              </view>
              <view v-else>
              <tm-icon :name="props.linkItem.icon||props.linkItem.iconImgUrl" :font-size="54" :color="props.linkItem.color"  _class="pb-10"></tm-icon>
              <zh-text _class="text-weight-b" parentClass="text-align-center" :font-size="28" :color="props.titleColor" :label="props.linkItem.title"></zh-text>
              </view>
            </slot>
          </view>
        </zh-badge>
      </view>
    </zh-sheet>
    <zh-message ref="messageRef" :duration="2000"></zh-message>
  </view>
</template>
<script lang="ts" setup>
/**
 * 九宫格子项目
 * @description 注意，它只能放置在zh-grid中，且不能嵌套zh-grid
 * @slot 默认插槽 任意内容
 */
import { computed, inject, provide, Ref, ref, watchEffect, getCurrentInstance, onBeforeUnmount, watch, nextTick, onMounted } from 'vue';
import { cssstyle } from '@/tool/lib/interface';
import { custom_props, computedTheme, computedClass, computedStyle, computedDark } from '@/tool/lib/minxs';
import * as u from '@/tool/function/util';
import systemConfigStore from '@/store/modules/systemConfigStore';
const store = systemConfigStore();
const emits = defineEmits(['click']);
const proxy = getCurrentInstance()?.proxy ?? null;
const props = defineProps({
  ...custom_props,
  //项目的高度。如果提供为0，就表示自动高度。
  height: {
    type: Number,
    default: 0,
  },
  transprent: {
    type: Boolean,
    default: false,
  },
  text: {
    type: Boolean,
    default: false,
  },
  dot: {
    type: [Boolean, String],
    default: false,
  },
  iconRound:{
    type: Number,
    default: 20,
  },
  icon: {
    type: [String],
    default: '',
  },
  //如果count为数字时，显示数字角标，如果为string是显示文本角标。
  count: {
    type: [Number, String],
    default: 0,
  },
  maxCount: {
    type: [Number, String],
    default: 999,
  },
  bgColor: {
    type: String,
    default: '',
  },
  // dot的主题色
  color: {
    type: String,
    default: 'red',
  },
  iconColor: {
    type: String,
    default: 'primary',
  },
  titleColor: {
    type: String,
    default: '',
  },
  //如果提供了链接，当点击项目时自动跳转页面。
  url: {
    type: String,
    default: '',
  },
  //如果提供了链接，当点击项目时自动跳转页面。
  linkItem: {
    type: Object,
    default: () => {},
  },
});
interface arrayid {
  id: string | number;
  type: string | number;
}
const messageRef = ref();
// 设置响应式全局组件库配置表。
const tmcfg = computed<any>(() => store);
//是否暗黑模式。
const isDark = computed(() => computedDark(props, tmcfg.value));
//计算主题
const zhcomputed = computed<cssstyle>(() => {
  return computedTheme({ ...props, color: props.bgColor }, isDark.value, tmcfg.value);
});

const _colWidth = inject('zhGridItemWidth', 0);
const _col= inject('zhGridCol', 5);
const _zhGridshowBorder = inject(
  'zhGridshowBorder',
  computed(() => false)
);
const zhGridshowCachList = inject(
  'zhGridshowCachList',
  computed<Array<arrayid>>(() => [])
);
const uid: Ref<arrayid> = ref({
  id: uni.$tm.u.getUid(1),
  type: '',
});
//父级方法。
let parentFormItem: any = proxy?.$parent;
while (parentFormItem) {
  if (parentFormItem?.keyName == 'zhGrid' || !parentFormItem) {
    break;
  } else {
    parentFormItem = parentFormItem?.$parent ?? undefined;
  }
}
onMounted(() => {
  if (parentFormItem?.pushKey) {
    parentFormItem.pushKey(uid.value);
  }
}),
  onBeforeUnmount(() => {
    parentFormItem?.delKey(uid.value);
  });
let wkStyle: any = ref(`width:${_colWidth}'rpx'`);

watch(
  [zhGridshowCachList, _zhGridshowBorder],
  () => {
    nextTick(() => setStyleFun());
  },
  { deep: true }
);

function setStyleFun() {
  let ar = zhGridshowCachList.value.filter((el) => el.id == uid.value.id);
  if (ar.length == 1) {
    uid.value = ar[0];
  }
  if (!_zhGridshowBorder.value) {
    wkStyle.value = `box-sizing: border-box;border:0rpx solid rgba(0,0,0,0);width:${_colWidth}rpx`;
    return;
  }

  if (uid.value.type == 1) {
    wkStyle.value = `box-sizing: border-box;border:1rpx solid ${zhcomputed.value.border};width:${_colWidth - 1}rpx`;
  }
  if (uid.value.type == 2) {
    wkStyle.value = `box-sizing: border-box;border-bottom:1rpx solid ${zhcomputed.value.border};border-right:1rpx solid ${
      zhcomputed.value.border
    };border-left:1rpx solid rgba(0,0,0,0);border-top:1rpx solid rgba(0,0,0,0);width:${_colWidth - 1}rpx`;
  }
  if (uid.value.type == 3) {
    wkStyle.value = `box-sizing: border-box;border-top:1rpx solid rgba(0,0,0,0);border-bottom:1rpx solid ${zhcomputed.value.border};border-right:1rpx solid ${
      zhcomputed.value.border
    };border-left:1rpx solid ${zhcomputed.value.border};width:${_colWidth - 1}rpx`;
  }
  if (uid.value.type == 4) {
    wkStyle.value = `box-sizing: border-box;border-left:1rpx solid rgba(0,0,0,0);border-bottom:1rpx solid ${zhcomputed.value.border};border-top:1rpx solid ${
      zhcomputed.value.border
    };border-right:1rpx solid ${zhcomputed.value.border};width:${_colWidth - 1}rpx`;
  }
}
function onClick(e: Event) {
  emits('click', e);
  if (props.url !== '') {
    try {
      uni.navigateTo({
        url: props.url,
      });
    } catch (e) {
      //TODO handle the exception
    }
  }

  let item = props.linkItem;
  let messageData: any = {};
  messageData.model = 'warn';
  messageData.dark = tmcfg.value.dark;
  if (!u.isEmpty(item)) {
    if (item.linkType) {
      if (item.linkType == 'router') {
        if (item.linkName) {
          let params: any = {};
          if (item.param1) {
            //自定义参数1为请求参数，不为空时传入
            try {
              params = JSON.parse(item.param1);
            } catch (e) {
              messageData.text = '功能配置异常，请求参数（param1）配置必须是json格式';
              messageRef.value.show(messageData);
              return;
            }
          }
          if (item.title) {
            params.headerTitle = item.title; //标题
          }
          if (item.menuId) {
            params.menuId = item.menuId; //菜单id
          }
          if (item.serviceCode) {
            params.serviceCode = item.serviceCode; //服务事项编码
          }
          if (item.serviceName) {
            params.serviceName = item.serviceName; //服务事项名称
          }
          let pages: any = uni.$tm.pages;
          let linkPath = item.linkPath;
          if (linkPath) {
            if (linkPath.startsWith('/')) {
              linkPath = linkPath.substring(1);
            }
          }
          if (linkPath && pages.get(linkPath)) {
            $router.push(item.linkPath, params);
          } else {
            messageData.text = '功能配置异常，未找到跳转页面';
            messageRef.value.show(messageData);
          }
        } else {
          messageData.text = '功能目前在测试中，尚未开放';
          messageRef.value.show(messageData);
        }
      } else if (item.linkType === 'h5' || item.linkType === 'openH5' || item.linkType === 'openh5' || item.linkType == 'h5_href') {
        if (item.linkUrl) {
          gotoOhterPage(item);
        } else {
          messageData.text = '功能目前在测试中，尚未开放';
          messageRef.value.show(messageData);
        }
      } else {
        messageData.text = '功能目前在测试中，尚未开放';
        messageRef.value.show(messageData);
      }
    } else {
      messageData.text = '功能目前在测试中，尚未开放';
      messageRef.value.show(messageData);
    }
  }
}
const gotoOhterPage = (item: any) => {
  const url = item.linkUrl;
  let messageData: any = {};
  messageData.model = 'warn';
  messageData.dark = store.dark;
  if (url) {
    let params: any = {};
    if (item.title) {
      params.headerTitle = item.title; //标题
    }
    if (item.menuId) {
      params.menuId = item.menuId; //菜单id
    }
    if (item.serviceCode) {
      params.serviceCode = item.serviceCode; //服务事项编码
    }
    if (item.serviceName) {
      params.serviceName = item.serviceName; //服务事项名称
    }
    params.url = encodeURIComponent(url);
    params.tokenFlag = item.tokenFlag;
    params.linkType = item.linkType;
    if (item.linkPath) {
      $router.push(item.linkPath, params);
    } else {
      $router.push('/pages/system/webView/webView', params);
    }
  } else {
    messageData.text = '没有传入跳转的链接';
    messageRef.value.show(messageData);
  }
};
</script>
